package za.org.jcicada.datastore.impl;

import java.net.URI;
import java.util.Date;

import za.org.jcicada.comms.IConnector;
import za.org.jcicada.comms.exceptions.CommsException;
import za.org.jcicada.comms.impl.MessageListenerBase;
import za.org.jcicada.comms.impl.ProxyBase;
import za.org.jcicada.datastore.IDataStoreClient;
import za.org.jcicada.datastore.IDataStoreServer;
import za.org.jcicada.datastore.messages.SensorHistoryReply;
import za.org.jcicada.datastore.messages.SensorHistoryRequest;
import za.org.jcicada.datastore.messages.StatusHistoryReply;
import za.org.jcicada.datastore.messages.StatusHistoryRequest;
import za.org.jcicada.genss.sensor.SensorURN;

public class DataStoreServerProxy extends ProxyBase<IDataStoreClient> implements IDataStoreServer {

    /**
     * Constructor passes connector to base class
     * 
     * @param connector connector used for creating connections
     * @throws CommsException
     */
    public DataStoreServerProxy(IConnector connector) {
        super(connector);
    }

    /**
     * Create a ConfigurationServerProxy.
     * 
     * @param locationURI address of the acceptor
     */
    public DataStoreServerProxy(URI locationURI) {
        super(locationURI);
    }

    @Override
    protected MessageListenerBase createReceiver(IDataStoreClient client) {
        return new Receiver(client);
    }

	public void requestSensorHistory(IDataStoreClient client, SensorURN sensorURN, Date from, Date to) {
		sendMessage(client, new SensorHistoryRequest(sensorURN, from, to));
	}
	
	public void requestStatusHistory(IDataStoreClient client, SensorURN sensorURN, Date from, Date to) {
		sendMessage(client, new StatusHistoryRequest(sensorURN, from, to));
	}

    /**
     * Implementation of IMessageListener that dispatches messages to an
     * IDataStoreClient.
     */
    public class Receiver extends MessageListenerBase {

        /**
         * Handle to callback object for messages from the subject to the
         * client.
         */
        IDataStoreClient client;

        public Receiver(IDataStoreClient client) {
            this.client = client;
        }

        public void onClose() throws Exception {
            client.informDisconnect();
        }

        // dispatch methods

        public void datastoreSensorHistoryReply(SensorHistoryReply msg) {
            client.replySensorHistory(msg.getResult(), msg.getSensorURN(), msg.getFrom(), msg.getTo(), msg.getValues());
        }
        
        public void datastoreStatusHistoryReply(StatusHistoryReply msg) {
        	client.replyStatusHistory(msg.getResult(), msg.getSensorURN(), msg.getFrom(), msg.getTo(), msg.getValues());
        }
    }
}
